import { RouteRecordRaw } from 'vue-router';
import util from '@/utils';
// 自动注册
const layouts = import.meta.globEager('../layouts/*.vue');
const views = import.meta.globEager('../views/**/*.vue'); // **表示所有目录
// 获取所有路由
function getRoutes() {
  const layoutRoutes = [] as RouteRecordRaw[];
  Object.entries(layouts).forEach(([file, module]) => {
    const route = getRouteByModule(file, module);
    route.children = getChildrenRoutes(route);
    layoutRoutes.push(route);
  });
  return layoutRoutes;
}
// 获取子路由
function getChildrenRoutes(layoutRoute: RouteRecordRaw) {
  const routes = [] as RouteRecordRaw[];
  Object.entries(views).forEach(([file, module]) => {
    if (file.includes(`../views/${layoutRoute.name as string}`)) {
      const route = getRouteByModule(file, module);
      routes.push(route);
    }
  });
  return routes;
}
// 获取单个路由
function getRouteByModule(file: string, module: { [key: string]: any }) {
  const name = file.replace(/.+layouts\/|.+views\/|\.vue/gi, '');
  const route = {
    name: name.replace('/', '.'),
    path: `/${name}`,
    component: module.default
  } as RouteRecordRaw;
  // 支持自定义路由
  return Object.assign(route, module.default?.route);
  // return route
}

// const routes = util.env.VITE_ROUTER_AUTOLOAD ? getRoutes() : [];
export default getRoutes;
